package com.service;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.widget.RemoteViews;

import com.util.HttpUtil;
import com.util.LogUtil;
import com.util.R;
import com.util.okhttputils.OkHttpUtils;
import com.util.okhttputils.callback.FileCallBack;

import java.io.File;

import okhttp3.Call;

/**
 * Created by marlon on 2016-05-13.
 */
public class UpdateApkService extends IntentService {
    private static NotificationManager notificationManager;
    private Notification notification;
    private RemoteViews rViews;
    private int newLoadProgress = 0;
    private int oldLoadProgress = 0;
    private static String CANCEL_TAG = "cancel";
    private static boolean isCancelUpdate = false;
    private Handler handler = new Handler();
    private Runnable run = new Runnable() {
        public void run() {
            if (isCancelUpdate) { //收到取消更新的广播
                handler.removeCallbacks(run);
                return;
            }
            if (newLoadProgress > oldLoadProgress) { //有进度更新
                oldLoadProgress = newLoadProgress;
                rViews.setProgressBar(R.id.pb_display_updateAPK, 100, newLoadProgress, false);
                rViews.setTextViewText(R.id.tv_tip_updateAPK, "正在下载 " + newLoadProgress + "%");
                notificationManager.notify(0, notification);
            }
            handler.postDelayed(run, 800);
            if (newLoadProgress >= 100) { //进度超过100
                handler.removeCallbacks(run);
                notificationManager.cancel(0);
                installApk();
            }
        }
    };


    public UpdateApkService() {
        super("com.service.UpdateApkService");
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        isCancelUpdate = false;
        initNotification();
        notificationManager.notify(0, notification); //发送通知
        // 开始下载
        HttpUtil.downLoadFile("http://android.pelway.cn/puhui_V1.1.6.apk", CANCEL_TAG, new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "普惠智能.apk") {
            @Override
            public void inProgress(float progress, long total) {
                newLoadProgress = (int) (100 * progress);
            }

            @Override
            public void onError(Call call, Exception e) {

            }

            @Override
            public void onResponse(File response) {

            }
        });
        handler.post(run); //更新通知栏

    }

    //安装Apk
    private void installApk() {
        Intent install = new Intent(Intent.ACTION_VIEW);
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "普惠智能.apk");
        if (file.exists()) {
            LogUtil.i("file", file.length());
        } else {
            LogUtil.i("file", "noFile");
        }
        install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(install);
    }

    //初始化通知
    private void initNotification() {
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notification = new Notification();
        notification.icon = R.mipmap.download;
        notification.flags = Notification.FLAG_NO_CLEAR; //设置无法清除
        rViews = new RemoteViews(getPackageName(), R.layout.view_update_apk);
        rViews.setImageViewResource(R.id.iv_cancelUpdateApk, R.mipmap.cancel);
        Intent intent = new Intent();
        intent.setAction("CancelUpdateApkReceiver");
        //点击取消更新发送广播
        rViews.setOnClickPendingIntent(R.id.iv_cancelUpdateApk, PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
        notification.contentView = rViews;
    }

    //接收广播,取消APK的更新
    public static class CancelUpdateApkReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            isCancelUpdate = true;
            notificationManager.cancel(0);
            OkHttpUtils.getInstance().cancelTag(CANCEL_TAG);
        }
    }

}
